﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Globalization;
using Com.CodePlex.SPPower.ViewModel;
using Com.CodePlex.SPPower.Data;
using Com.CodePlex.SPPower.View;
using System.Diagnostics;
using System.Windows.Threading;

namespace Com.CodePlex.SPPower {

	public partial class App : Application {

		protected override void OnStartup(StartupEventArgs e) {
			base.OnStartup(e);

			if (!System.Diagnostics.Debugger.IsAttached) {
				DispatcherUnhandledException += AppDispatcherUnhandledException;
				AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
			}

			MainWindowViewModel model = new MainWindowViewModel();
			MainWindowView window = new MainWindowView();
			window.DataContext = model;
			window.Show();
		}

		private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
			HandleException(e.Exception, false);
			e.Handled = true;
		}

		private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) {
			HandleException(e.ExceptionObject as Exception, e.IsTerminating);
		}

		private static void HandleException(Exception e, bool isterminating) {
			if (e == null) { 
				return; 
			}
			Trace.TraceError(e.ToString());
			if (!isterminating) {
				MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Unknown Application Error\r\n\r\n{0}", e.ToString()), 
					MainWindowViewModel.APPLICATION_NAME, 
					MessageBoxButton.OK, 
					MessageBoxImage.Error);
			}
		}
	}
}
